package com.shenyuan.module_basekt.base

import android.os.Parcel
import android.os.Parcelable
import com.alibaba.fastjson.JSONException
import io.reactivex.subscribers.DisposableSubscriber
import retrofit2.HttpException
import java.io.InterruptedIOException
import java.net.ConnectException
import java.net.UnknownHostException
import java.text.ParseException

/**
 * @author ch
 * @date 2022/7/18-14:31
 * desc
 */
class BaseVMSubscriber<T>() : DisposableSubscriber<T>() {

    val liveData = BaseLiveData<BaseResult<T>>()

    var isShowDialog = false;

    constructor(isShow: Boolean) : this() {
        this.isShowDialog = isShow
    }


    companion object {
        const val CODE_SUCC = "A01"
        const val CODE_SHOW_LODING = "A02"
        const val CODE_CLOSE_LODING = "A03"
        const val CODE_LOGIN_OUT = "A04"
        const val CODE_BAD_NETWORK = "A05"
        const val CODE_CONNECT_ERROR = "A06"
        const val CODE_CONNECT_TIMEOUT = "A07"
        const val CODE_PARSE_ERROR = "A08"
        const val CODE_OTHER_ERROR = "A09"

        /**
         * 解析数据失败
         */
        const val PARSE_ERROR_MSG = "数据解析失败"

        /**
         * 网络问题
         */
        const val BAD_NETWORK_MSG = "网络问题，请稍后再试"

        /**
         * 连接错误
         */
        const val CONNECT_ERROR_MSG = "连接错误，请稍后再试"

        /**
         * 连接超时
         */
        const val CONNECT_TIMEOUT_MSG = "连接超时，请稍后再试"

        /**
         * 未知错误
         */
        const val OTHER_MSG = "未知错误，请稍后再试"
    }


    override fun onStart() {
        super.onStart()
        if (isShowDialog) {
            postValue(CODE_SHOW_LODING, "显示加载动画")
        }
    }

    override fun onNext(t: T) {
        postValue(CODE_SUCC, "请求成功", t)
    }

    override fun onError(t: Throwable?) {
        if (t == null) {
            postValue(CODE_OTHER_ERROR, OTHER_MSG)
        } else {
            if (t is HttpException) {
                //   HTTP错误
                postValue(CODE_BAD_NETWORK, BAD_NETWORK_MSG)
            } else if (t is ConnectException || t is UnknownHostException) {
                //   连接错误
                postValue(CODE_CONNECT_ERROR, CONNECT_ERROR_MSG)
            } else if (t is InterruptedIOException) {
                //  连接超时
                postValue(CODE_CONNECT_TIMEOUT, CONNECT_TIMEOUT_MSG)
            } else if (t is JSONException || t is ParseException) {
                //  解析错误
                postValue(CODE_PARSE_ERROR, PARSE_ERROR_MSG)
            } else {
                postValue(CODE_OTHER_ERROR, t.message)
            }
        }
    }

    override fun onComplete() {
    }

    private fun postValue(code: String, msg: String?) {
        postValue(code, msg, null)
    }


    private fun postValue(code: String, msg: String?, t: T?) {
        liveData.postValue(BaseResult(code, msg, t))
    }

}